package org.jeecg.modules.gift.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.config.shiro.IgnoreAuth;
import org.jeecg.modules.gift.entity.*;
import org.jeecg.modules.gift.service.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: 活动
 * @Author: jeecg-boot
 * @Date: 2024-07-10
 * @Version: V1.0
 */
@Api(tags = "活动")
@RestController
@RequestMapping("/gift/giftActivity")
@Slf4j
public class GiftActivityController extends JeecgController<GiftActivity, IGiftActivityService> {
    @Autowired
    private IGiftActivityService giftActivityService;
    @Autowired
    private IGiftActivityUserService giftActivityUserService;
    @Autowired
    private IGiftActivityMerchantService giftActivityMerchantService;
    @Autowired
    private IGiftProductInfoService giftProductInfoService;
    @Autowired
    private IGiftActivityClockinService giftActivityClockinService;


    @ApiOperation(value = "活动-小程序分页", notes = "活动-小程序分页")
    @GetMapping(value = "/list/mini")
    @IgnoreAuth
    public Result<IPage<GiftActivity>> miniPageList(GiftActivity giftActivity,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<GiftActivity> queryWrapper = QueryGenerator.initQueryWrapper(giftActivity, req.getParameterMap());
        Page<GiftActivity> page = new Page<GiftActivity>(pageNo, pageSize);
        IPage<GiftActivity> pageList = giftActivityService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 活动详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "活动详情", notes = "活动详情")
    @GetMapping(value = "/details")
    public Result<GiftActivityDetail> details(@RequestParam(name = "id") String id) {
        GiftActivity activity = giftActivityService.getById(id);
        if (activity == null)
            return Result.error("活动不存在");

        GiftActivityDetail detail = GiftActivityDetail.create(activity);

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = sysUser.getId();

        LambdaQueryWrapper<GiftActivityUser> query = new LambdaQueryWrapper<GiftActivityUser>();
        query.eq(GiftActivityUser::getUserId, userId);
        query.eq(GiftActivityUser::getActivityId, id);
        detail.setUserStatus(giftActivityUserService.count(query) > 0 ? 1 : 0);

        return Result.OK(detail);
    }

    /**
     * 当前活动
     * @return
     */
    @ApiOperation(value = "当前活动", notes = "当前活动")
    @GetMapping(value = "/current")
    public Result<Map> current() {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = sysUser.getId();

        LambdaQueryWrapper<GiftActivityUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GiftActivityUser::getUserId, userId);
        queryWrapper.in(GiftActivityUser::getJoinStatus,Arrays.asList("1","2","3"));
        GiftActivityUser activityUser = giftActivityUserService.getOne(queryWrapper, false);


        Map<String, Object> map = new HashMap<>();
        if (activityUser == null) {
            map.put("activityId", 0);
            map.put("total", 0);
            map.put("complete", 0);
        } else {

            List<GiftMerchantProgress> list = giftActivityClockinService.selectActivityClockinList(activityUser.getActivityId(), userId);
            map.put("activityId", activityUser.getActivityId());
            long complete = list.stream().filter(item -> item.getIsJoin() == 1).count();
            map.put("complete", complete);
            map.put("total", list.size());
        }

        return Result.OK(map);
    }

    /**
     * 活动进度
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "活动进度", notes = "活动进度")
    @GetMapping(value = "/progress")
    public Result<List<GiftMerchantProgress>> progress(@RequestParam(name = "id") String id) {
        GiftActivity activity = giftActivityService.getById(id);
        if (activity == null)
            return Result.error("活动不存在");

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String userId = sysUser.getId();

        return Result.OK(giftActivityClockinService.selectActivityClockinList(id, userId));
    }


    /**
     * @param activityId
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "活动参与用户-分页列表查询", notes = "活动参与用户-分页列表查询")
    @GetMapping(value = "/users")
    public Result<IPage<GiftActivityUserItem>> queryUserList(@RequestParam(name = "activityId", required = true) String activityId,
                                                             @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                             @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                             HttpServletRequest req) {
        Page<GiftActivityUserItem> page = new Page<GiftActivityUserItem>(pageNo, pageSize);
        IPage<GiftActivityUserItem> pageList = giftActivityUserService.selectPageActivityUserList(page, activityId);
        return Result.OK(pageList);
    }

    /**
     * @param activityId
     * @param req
     * @return
     */
    @ApiOperation(value = "活动参与商家", notes = "活动参与商家")
    @GetMapping(value = "/merchants")
    public Result<List<GiftMerchant>> queryMerchantList(@RequestParam(name = "activityId", required = true) String activityId,
                                                        HttpServletRequest req) {

        List<GiftMerchant> pageList = giftActivityMerchantService.selectActivityMerchantList(activityId);
        return Result.OK(pageList);
    }

    /**
     * @param activityId
     * @param req
     * @return
     */
    @ApiOperation(value = "活动奖品", notes = "活动奖品")
    @GetMapping(value = "/product")
    public Result<List<GiftProductInfo>> queryProductList(@RequestParam(name = "activityId", required = true) String activityId,
                                                          HttpServletRequest req) {

        List<GiftProductInfo> pageList = giftProductInfoService.list();
        return Result.OK(pageList);
    }


    /**
     * 分页列表查询
     *
     * @param giftActivity
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "活动-分页列表查询")
    @ApiOperation(value = "活动-分页列表查询", notes = "活动-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<GiftActivity>> queryPageList(GiftActivity giftActivity,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                     HttpServletRequest req) {
        QueryWrapper<GiftActivity> queryWrapper = QueryGenerator.initQueryWrapper(giftActivity, req.getParameterMap());
        Page<GiftActivity> page = new Page<GiftActivity>(pageNo, pageSize);
        IPage<GiftActivity> pageList = giftActivityService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param giftActivity
     * @return
     */
    @AutoLog(value = "活动-添加")
    @ApiOperation(value = "活动-添加", notes = "活动-添加")
    @RequiresPermissions("gift:gift_activity:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody GiftActivity giftActivity) {
        giftActivityService.save(giftActivity);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param giftActivity
     * @return
     */
    @AutoLog(value = "活动-编辑")
    @ApiOperation(value = "活动-编辑", notes = "活动-编辑")
    @RequiresPermissions("gift:gift_activity:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody GiftActivity giftActivity) {
        giftActivityService.updateById(giftActivity);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "活动-通过id删除")
    @ApiOperation(value = "活动-通过id删除", notes = "活动-通过id删除")
    @RequiresPermissions("gift:gift_activity:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        giftActivityService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "活动-批量删除")
    @ApiOperation(value = "活动-批量删除", notes = "活动-批量删除")
    @RequiresPermissions("gift:gift_activity:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.giftActivityService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "活动-通过id查询")
    @ApiOperation(value = "活动-通过id查询", notes = "活动-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<GiftActivity> queryById(@RequestParam(name = "id", required = true) String id) {
        GiftActivity giftActivity = giftActivityService.getById(id);
        if (giftActivity == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(giftActivity);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param giftActivity
     */
    @RequiresPermissions("gift:gift_activity:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, GiftActivity giftActivity) {
        return super.exportXls(request, giftActivity, GiftActivity.class, "活动");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("gift:gift_activity:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, GiftActivity.class);
    }

}
